//
//  YTController.m
//  YuTouSeeder
//
//  Created by Huang Dong on 10-9-21.
//  Copyright 2010 limboworks.com. All rights reserved.
//

#import "YTController.h"


@implementation YTController

-(id)init{
	[super init];
	NSMutableDictionary * defaultPrefs = [NSMutableDictionary dictionary];
	current =[[CurrentGet alloc]init];
	ytsite= [[YTSite alloc]init];
	
	[defaultPrefs setObject:@"" forKey:@"UserName"];
	[defaultPrefs setObject:@"" forKey:@"PassWord"];
	[defaultPrefs setValue:[NSNumber numberWithInt:1] forKey:@"CheckItunes"];
	[defaultPrefs setObject:@"Mac's Limbo" forKey:@"Location"];
	
	prefs = [[NSUserDefaults standardUserDefaults] retain];
	
	[prefs registerDefaults:defaultPrefs];
	
	return self;
}

-(void)dealloc{
	[prefs release];
	[current release];
	[super dealloc];
}

-(void)awakeFromNib{
	[usernameField setStringValue:[prefs stringForKey:@"UserName"]];
	[passwordField setStringValue:[prefs stringForKey:@"PassWord"]];
	[checkItunesField setState:[prefs integerForKey:@"CheckItunes"]];
	[locationField setStringValue:[prefs stringForKey:@"Location"]];
	aGrowlController = [[GrowlController alloc] init];
	[aGrowlController registerGrowl];	
}

- (IBAction) prefsFieldChanged:(id)sender{
	[prefs setObject:[usernameField stringValue] forKey:@"UserName"];
	[prefs setObject:[passwordField stringValue] forKey:@"PassWord"];
	[prefs setInteger:[checkItunesField state] forKey:@"CheckItunes"];
	[prefs setObject:[locationField stringValue] forKey:@"Location"];
}


- (void) updateTimerToRef:(NSTimer *) timer {
	[self sendMessage];
}

- (void) sendMessage {
	if ([prefs boolForKey:@"CheckItunes"]) {
		NSString *returnString = [current CurrentItunes];
		NSLog(@"current itunes:%@",returnString);
		if (![returnString isEqualToString:@"None"]) {
			[lastSeedField setStringValue:returnString];
			if([ytsite loginByUsername:[prefs stringForKey:@"UserName"] PassWord:[prefs stringForKey:@"PassWord"]]){
				[ytsite checkinVerb:@"听" Noun:returnString Location:[prefs stringForKey:@"Location"]];	
				[GrowlController notifyGrowlItunes:[NSString stringWithFormat:@"Play %@",returnString]];
			}else {
				NSLog(@"login error:%@",ytsite.error);
				[GrowlController notifyGrowlLoginError:ytsite.error];
			}
			
		}
	}	
}

-(IBAction)checkinNow:(id)sender{
	if (sender == seedAutoButton) {
		if (timerToRef) {
			[sender setTitle:@"Start AutoSeed"];
			[timerToRef invalidate];
		}else {
			[sender setTitle:@"Stop AutoSeed"];
			timerToRef = [NSTimer scheduledTimerWithTimeInterval:5
														  target:self 
														selector:@selector(updateTimerToRef:)
														userInfo:nil
														 repeats:YES];			
		}
		[self sendMessage];
	}
}

@end
